<?php /** @noinspection ALL */
/** @noinspection PhpUndefinedClassInspection */

/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020-6-10 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\modules\backend\controllers;

use common\models\UserAccountBook;
use common\models\UserDepositBook;
use common\models\UserExtend;
use common\models\UserRewardBook;
use Yii;
use yii\data\Pagination;
use yii\db\StaleObjectException;
use api\controllers\AuthAdminController;
use common\models\PubinMoney;
use common\models\PubinMoneyForm;
use common\models\User;

/**
 * 后台用户接口 controller for the `backend` module
 */
class UserController extends AuthAdminController
{
    /**
     * 获取列表
     * @return mixed
     */
    public function actionList()
    {
        $sort = trim(Yii::$app->getRequest()->get('sort'));
        $uid = intval(Yii::$app->getRequest()->get('uid'));
        $sex = trim(Yii::$app->getRequest()->get('sex'));
        $limit = intval(Yii::$app->getRequest()->get('limit', Yii::$app->config->getSiteItem('defaultPageSize')));
        switch ($sort) {
            case '-id':
                $orderBy['{{%user}}.id'] = SORT_DESC;
                break;
            case '+id':
                $orderBy['{{%user}}.id'] = SORT_ASC;
                break;
            default:
                $orderBy['{{%user}}.id'] = SORT_DESC;
        }
        $where = [];
        if ($uid) {
            $where['{{%user}}.id'] = $uid;
        }
        if ($sex !== '') {
            $where['sex'] = (int) $sex;
        }

        $query = User::find()
            ->orderBy($orderBy);
        $count = $query->count();
        $pagination = new Pagination(['totalCount' => $count, 'defaultPageSize' => $limit]);

        $uTbl = User::tableName();
        $data = $query->select(["{$uTbl}.id", 'country_code', 'mobile', 'nickname', 'avatar', 'status', 'user_status'])
            ->where($where)
            ->joinWith(['userExtend' => function($q) {
                $extTbl = UserExtend::tableName();
                return $q->select(['uid', 'sex']);
            }])
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->asArray()
            ->all();

        $page = (int) $pagination->getPageCount();
        $total = (int) $pagination->totalCount;
        unset($query, $pagination);
        return Yii::$app->api->success(['total' => $total, 'pageCount' => $page, 'items' => $data]);
    }

    /**
     *用户详情数据
     */
    public function actionDetail()
    {
        $uid = Yii::$app->getRequest()->get('uid');
        $data = User::getUserDetailOnBackend($uid);

        return Yii::$app->api->success((array) $data);
    }
}
